package com.kerong.chedeli.view.home;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kerong.chedeli.CheDeLiApplication;
import com.kerong.chedeli.R;
import com.kerong.chedeli.utils.AppManager;
import com.kerong.chedeli.utils.PreferencesUtils;
import com.kerong.chedeli.view.BaseActivity;
import com.kerong.chedeli.view.BaseFragment;
import com.kerong.chedeli.view.UIHelper;
import com.kerong.chedeli.view.driver.CarEarningActivity;
import com.kerong.chedeli.view.driver.SendCarActivity;
import com.kerong.chedeli.view.tenant.OrderListActivity;
import com.kerong.chedeli.view.tenant.SelectCarBigListFragment;
import com.kerong.chedeli.view.tenant.SelectCarListFragment;
import com.kerong.chedeli.view.tenant.SelectCarMapFragment;
import com.kerong.chedeli.view.user.LoginActivity;
import com.kerong.chedeli.widget.popwindowtime.TimePopupWindow;
import com.orhanobut.logger.Logger;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * 主界面布局
 */
public class MainActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.content_frame)
    FrameLayout content_frame;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.left_menu)
    RelativeLayout left_menu;
    @Bind(R.id.tv_use_time)
    TextView tvUseTime;
    @Bind(R.id.tv_total_order)
    TextView tvTotalOrder;
    @Bind(R.id.tv_total_area)
    TextView tvTotalArea;
    @Bind(R.id.tv_use_money)
    TextView tvUseMoney;
    @Bind(R.id.user_name)
    TextView user_name;
    @Bind(R.id.bt_logout)
    Button bt_logout;
    private ActionBarDrawerToggle mDrawToggle;
    private List<BaseFragment> searchFragmentList = new ArrayList<BaseFragment>();
    private List<Integer> searchResList = new ArrayList<Integer>();
    FragmentManager fm = null;
    private int current_index = 0;
    BaseFragment baseFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData();
    }

    private void initData() {
        initLogiStatus();
        fm = getSupportFragmentManager();
        //初始化选择Frgment
        searchFragmentList.add(new SelectCarListFragment());
        searchFragmentList.add(new SelectCarBigListFragment());
        searchFragmentList.add(new SelectCarMapFragment());
        //初始化对应的头部图片资源
        searchResList.add(R.mipmap.ic_big_list);
        searchResList.add(R.mipmap.ic_map_list);
        searchResList.add(R.mipmap.ic_pubu_list);
        initActionBar();
        if(baseFragment == null){
            baseFragment = searchFragmentList.get(0);
            fm.beginTransaction()
                    .replace(R.id.content_frame, baseFragment)
                    .commit();

        }
    }
    private void initLogiStatus(){
        if(PreferencesUtils.getBoolean(this, CheDeLiApplication.PRE_LOGIN_STATUS,false)){
            user_name.setText("小金豆");
            bt_logout.setVisibility(View.VISIBLE);
        }else{
            user_name.setText("请点击登录");
            bt_logout.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.bt_logout)
    public void onLogoutClick(){
        PreferencesUtils.putBoolean(this, CheDeLiApplication.PRE_LOGIN_STATUS, false);
        initLogiStatus();
    }
    @OnClick({R.id.tv_use_time,R.id.tv_total_order,R.id.tv_total_area,R.id.tv_use_money})
    public void onSearhItemClick(TextView item){
        switch (item.getId()){
            case R.id.tv_use_time:
                TimePopupWindow timePopupWindow = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
                timePopupWindow.showAsDropDown(tvUseTime, 0, 0);
                timePopupWindow.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date loanTime, Date backTime) {
                        Logger.i("设置的时间是"+loanTime.toLocaleString()+"---"+backTime.toLocaleString());
                    }
                });
                break;
            case R.id.tv_total_order:
                break;
            case R.id.tv_total_area:
                break;
            case R.id.tv_use_money:
                break;
        }
    }

    @OnClick({R.id.tv_select_car, R.id.tv_order, R.id.tv_sendcar, R.id.tv_money})
    public void menuClick(final TextView menuItem) {
        drawerLayout.closeDrawers();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                switch (menuItem.getId()) {
                    case R.id.tv_select_car:
                        baseFragment = searchFragmentList.get(current_index);
                        fm.beginTransaction()
                                .replace(R.id.content_frame, baseFragment)
                                .commit();

                        break;
                    case R.id.tv_order:
                        turnToActivity(OrderListActivity.class);
                        break;
                    case R.id.tv_sendcar:
                        turnToActivity(SendCarActivity.class);
                        break;
                    case R.id.tv_money:
                        turnToActivity(CarEarningActivity.class);
                        break;
                }
            }
        }, 200);


    }

    @OnClick(R.id.user_container)
    public void onUserLoginClick(View item){
        if(PreferencesUtils.getBoolean(this,CheDeLiApplication.PRE_LOGIN_STATUS)){
            return;
        }
        drawerLayout.closeDrawers();
        turnToActivity(LoginActivity.class);
    }
    private void initActionBar() {
        toolbar.setNavigationIcon(R.mipmap.ic_launcher);
        setSupportActionBar(toolbar);
        //getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        //设置ActionBar的左侧切换动画效果
        mDrawToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                supportInvalidateOptionsMenu();
            }


            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                //getSupportActionBar().setTitle(getResources().getString(R.string.app_name));
                supportInvalidateOptionsMenu();
            }


        };
        drawerLayout.setDrawerListener(mDrawToggle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawToggle.onOptionsItemSelected(item)) {
            return true;
        }
        switch (item.getItemId()) {
            case R.id.menu_search:
                Logger.i("执行搜索界面");
                UIHelper.showSearch(this,false);
                break;
            case R.id.menu_change:
                current_index++;
                if(current_index == 3){
                    current_index = 0;
                }
                Logger.i("执行查询界面的切换当前界面"+searchFragmentList.get(current_index).getClass().getSimpleName());
                fm.beginTransaction()
                        .replace(R.id.content_frame, searchFragmentList.get(current_index))
                        .commit();
                item.setIcon(searchResList.get(current_index));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void onEvent(String event){
        if(event.equals("user")){
            initLogiStatus();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK ){
            exit();//双击退出
        }
        return false;

    }
    boolean isExit = false;
    private void exit(){
        Timer timer = null;
        if(!isExit){
            isExit  = true;
            Toast.makeText(this, R.string.exit_text, Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            },2000);
        }else{
            AppManager.getAppManager().AppExit(this);
        }

    }
}
